package 剑指offer.demo7;

import java.util.Collections;
import java.util.PriorityQueue;

//https://leetcode.cn/problems/kth-smallest-element-in-a-bst/
public class 二叉搜索树中第K小的元素 {
    PriorityQueue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder());
    public int kthSmallest(TreeNode root, int k) {
        fun(root , k);
        return queue.poll();
    }
    public void fun (TreeNode root , int k){
        if (queue.size() < k) {
            queue.offer(root.val);
        }else {
            if (queue.peek() > root.val){
                queue.poll();
                queue.offer(root.val);
            }
        }
        if (root.left != null){
            fun(root.left , k);
        }
        if (root.right != null){
            fun(root.right , k);
        }
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
